package qz.lixinyu.common.upload;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import qz.lixinyu.common.utils.R;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@RestController
@RequestMapping("file")
public class FileUpload {


    @Value("${web.upload-path}")
    private String uploadPath;



    //头像上传到本地服务器
    @RequestMapping("/upload")
    public R upload3(MultipartFile file, HttpServletRequest req) throws IOException, NoSuchAlgorithmException {
        // 本地上传
        // 计算文件的哈希值
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[8192];
        int bytesRead;
        try (InputStream fis = file.getInputStream()) {
            while ((bytesRead = fis.read(buffer)) != -1) {
                md.update(buffer, 0, bytesRead);
            }
        }
        byte[] digest = md.digest();
        StringBuilder sb = new StringBuilder();
        for (byte b : digest) {
            sb.append(String.format("%02x", b));
        }
        // 提取文件后缀
        String originalFilename = file.getOriginalFilename();
        String fileExtension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }

        // 构建包含后缀的文件哈希名
        String fileHash = sb.toString() + fileExtension;

        // 构建本地文件路径
        File localFile = new File(uploadPath + fileHash);
        // 检查文件是否已存在
        if (!localFile.exists()) {
            // 创建存储目录（如果不存在）
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            // 将文件保存到本地
            try (OutputStream fos = new FileOutputStream(localFile)) {
                fos.write(file.getBytes());
            }
        }

        // 假设访问本地文件的基础 URL，根据实际情况修改
        // 返回上传文件的访问路径
        String filePath = req.getScheme() + "://" + req.getServerName()
                + ":" + req.getServerPort() +"/"  + fileHash;
        /*System.out.println("文件地址:"+ folder+newName);*/
        R r =new R();
        r.put("url",filePath);
        return R.ok(r);
    }
}
